import os
from PIL import Image
from PIL import ImageDraw
import math

from core import *

def create(card:Card) -> Image.Image:
    """
    still shit code 
    i dont want to edit it D=
    """
    # prepare front and back
    front = card.front.copy()
    back = card.back.copy()
    # prepare abilites
    if len(card.abilities) > 2: abilities = card.abilities[:2]
    else: abilities = card.abilities
        
    if len(abilities) == 2:
        ab_count = 2
        ab_0 = abilities[0].resize((round(abilities[0].size[0]*0.70), round(abilities[0].size[0]*0.70)))
        ab_1 = abilities[1].resize((round(abilities[1].size[1]*0.70), round(abilities[1].size[1]*0.70)))
        
    elif len(abilities) == 1:
        ab_count = 1
        ab_0 = abilities[0]
        ab_1 = None        
    else:
        ab_count = 0
        ab_0 = None
        ab_1 = None
    
    # beast
    front.paste(card.beast,(7,32),card.beast)

    # abilities
    if ab_count == 1:
        front.paste(ab_0,(40,133),ab_0)
    elif ab_count == 2:
        front.paste(ab_0,(32,150),ab_0)
        front.paste(ab_1,(57,132),ab_1)
    # cost
    if card.cost:
        cost = card.cost.resize((math.floor(card.cost.size[0]*0.75),math.floor(card.cost.size[1]*0.75)))
        x, y = 119 - cost.size[0], 23
        front.paste(cost,(x,y),cost)

    # then decals
    if card.decal:
        front.paste(card.decal,(0,0),card.decal)
        
    # then we need to turn front into a image draw thing to put text on it
    draw_front = ImageDraw.Draw(front)
    # name
    draw_front.text(xy=(62,16),text=card.name.text,fill=(0,0,0),font=card.name.font,anchor="mm")
    # damage & health
    if card.show_damage:
        draw_front.text(xy=(19,150),text=card.damage.text,fill=(0,0,0),font=card.damage.font,anchor="mm")
    if card.show_health:
        draw_front.text(xy=(106,165),text=card.health.text,fill=(0,0,0),font=card.health.font,anchor="mm")
    
    return front, back

def safe_result(result:str) -> None:
    type = "card"
    target = os.path.realpath(os.path.join(
        result, type
    ))
    os.makedirs(target, exist_ok=True)
    target = os.path.realpath(os.path.join(
        target, "back"
    ))
    os.makedirs(target, exist_ok=True)

def output(base:str,name:str ,front:Image.Image, back:Image.Image) -> None:
    safe_result(base)
    fmt = os.path.realpath(os.path.join(base,"card","{}.png".format(name)))
    fmt_back = os.path.realpath(os.path.join(base,"card","back","{}.png".format(name)))
    
    front.save(fmt,"png",bitmap_format="png")
    back.save(fmt_back,"png",bitmap_format="png")